from django.shortcuts import render

from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.serializers import Good_Serializer
from orders.models import *
from orders.serializers import *


class Page(PageNumberPagination):
    page_size_query_param = 'pagesize'
    page_query_param = 'page'  # 页码查询参数
    page_size = 3   #默认的每页展示数据条数

# 订单的视图
class OrderInfoViewSet(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfo_Serializer
    lookup_url_kwarg = 'pk'
    lookup_field = 'pk'

    # 重写retrieve检索 返回要求的json数据
    def retrieve(self, request, *args, **kwargs):
        # 1 查询当前订单对象
        order = self.get_object()
        order_ser = OrderInfo_Serializer(order)

        # 2 反向查订单中的所有商品
        order_goods = order.orderGoods.all()
        # print('订单及订单商品', order, '/////订单商品', order_goods)
        order_goods_ser = OrderGood_Serializer(order_goods, many=True)

        # 3 修改订单商品的sku属性     order_goods_ser 的数据是 [{},{},{},{},]
        temp = []
        for i in order_goods_ser.data:
            i['sku'] = Good_Serializer(Good.objects.filter(id=i.get('sku')).first()).data

            # 存入一个临时列表
            temp.append(i)

        # 4 增加订单 字典的 skus 属性
        order_dict = order_ser.data
        order_dict['skus'] = temp

        return Response(order_dict)

    # 重写update
    def update(self, request, *args, **kwargs):
        # 1 接手前端数据
        status = request.data.get('status')

        # 2 获取要更新的对象
        order = self.get_object()

        # 3 更新状态
        order.status = status
        order.save()

        return Response({'code':200, 'msg': '更新状态成功'})







